package com.hp.bon.sgw.wh.processor;

import com.alibaba.fastjson.JSONObject;
import com.hp.bon.sgw.Constants;
import com.hp.bon.sgw.bean.XmlMessage;
import com.hp.bon.sgw.core.CallParam;
import com.hp.bon.sgw.core.processor.Processor;
import com.hp.bon.sgw.util.Comutils;
import com.hp.bon.sgw.wh.service.WHConfigService;
import com.hp.bon.sgw.wh.util.DateUtil;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.lang.StringEscapeUtils;
import org.dom4j.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Comments:TODO
 * 
 * @author :fengr Create Date：2019年7月8日 Version:<v1.0>
 */
public class WebServiceProcessor extends Processor {
	private static final Logger logger = LoggerFactory.getLogger(WebServiceProcessor.class);
	private String LBSYCXURL = "";
	private String ZDCXURL = "";
	private String YECXURL = "";
	private String YECXURLWH = "";
	private String RATABLE_RESOURCE_QUERY_URLjf3 ="";
    private String RATABLE_RESOURCE_QUERY_DETAIL_URLjf3 ="";
	private WHConfigService whConfigService;

	public void init() {
		LBSYCXURL = whConfigService.getValue("LBSYCXURL", "");
		ZDCXURL = whConfigService.getValue("ZDCXURL", "");
		YECXURL = whConfigService.getValue("YECXURL", "");
		YECXURLWH = whConfigService.getValue("YECXURLWH", "");
        RATABLE_RESOURCE_QUERY_URLjf3= whConfigService.getValue("RATABLE_RESOURCE_QUERY_URLjf3", "");
        RATABLE_RESOURCE_QUERY_DETAIL_URLjf3= whConfigService.getValue("RATABLE_RESOURCE_QUERY_DETAIL_URLjf3", "");
	}

	@Override
	public int process(CallParam callParam) {
		logger.info("===========start WebServiceProcessor===============");
		XmlMessage request = (XmlMessage) callParam.getRequest();
		try {
            String resp;
            //量本使用量和明细 ,改http请求
            if ("AccuUseQry.NEW.JF3".equals(callParam.getCapability()) ) {
                resp=sendWebSevice2(callParam,request.getDATA(),RATABLE_RESOURCE_QUERY_URLjf3);
            }else if ( "AccuUseDetailQry.NEW.JF3".equals(callParam.getCapability())) {
                resp=sendWebSevice2(callParam,request.getDATA(),RATABLE_RESOURCE_QUERY_DETAIL_URLjf3);
            }else if("QueryBalance.NEW.JF3".equals(callParam.getCapability())){
                //无鉴权,直接跳转
                resp=request.getDATA();
            }else{
                resp=sendWebService(callParam, request.getDATA(),request.getSIG());
            }

            if(!"QueryBalance.NEW.JF3".equals(callParam.getCapability())){
                //非 余额查询 中的宽带查询
                resp = StringEscapeUtils.unescapeXml(resp);
                resp=resp.replace("<?xml version=\"1.0\" encoding=\"GBK\"?>", "");
            }

			if (resp.equals("")) {
				callParam.setRetCode(1200);
				callParam.setResultMsg("time out");
            } else {
				XmlMessage ack = new XmlMessage(false);
				if (!resp.isEmpty()) {
					XmlMessage message = (XmlMessage) callParam.getRequest();
					String mid = message.getMID();
					Document docResp = Comutils.parseText(resp);
					ack.setDataElement(docResp.getRootElement());
					ack.setMID(mid.substring(0, mid.length() - 1));
					ack.setREPTAG(0);
					ack.setRTT(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(Long.valueOf(System.currentTimeMillis())));
					ack.setSIG(null);
					ack.setRC("0");
					ack.setDS("SUCCESS");
					ack.setDATA(resp);
					callParam.setRetCode(0);
					callParam.setServiceResultCode(0);
					callParam.setRecvResponse(ack);
				}
            }
            callParam.getAsynHandler().onCallResult(callParam);
        } catch (Exception e1) {
			logger.error("",e1);
		}
		return 0;
	}
	
	

	private String sendWebService(CallParam callParam, String param , String SIG) {
		String url = null;
		int timeOut = 5000;
		if ("BillDetailQuery.BillYXHB9.NEW".equals(callParam.getCapability()) || "QryInstantFeeList.NEW".equals(callParam.getCapability())) {
			url = ZDCXURL;
			timeOut = 10000;
		}
		// 量本使用查询(下游webservice接口)
		if ("AccuUseQry.NEW".equals(callParam.getCapability())) {
			url = LBSYCXURL;
			timeOut = 10000;
		}
		// 量本使用查询(下游webservice接口)
		if ("AccuUseDetailQry.NEW".equals(callParam.getCapability())) {
			url = LBSYCXURL;
			timeOut = 10000;
		}
		// 余额查询(下游webservice接口)
		if ("QueryBalance.NEW".equals(callParam.getCapability())) {
			url = YECXURLWH;
			timeOut = 10000;
		}
		//通用配置webService
		if ("PublicWebService.NEW".equals(callParam.getCapability())) {
			url = SIG;
			timeOut = 10000;
		}

		logger.info("===========WebServiceProcessor url===============" + url);
		logger.info("===========WebServiceProcessor param===============" + param);
        logger.info("=============send_request_time:"+ DateUtil.DateToStr(new Date(), "yyyy-MM-dd HH:mm:ss"));
		String resp = "";
		PostMethod post = new PostMethod(url);
		try {
			RequestEntity requestEntity = new StringRequestEntity(param, "text/xml", "UTF-8");
			post.setRequestEntity(requestEntity);
//            post.addRequestHeader( "Connection", "close");//Too many open files 解决
			HttpClient client = new HttpClient();
			client.getHttpConnectionManager().getParams().setConnectionTimeout(5 * 1000);// 设置连接超时时间，单位毫秒
			client.getHttpConnectionManager().getParams().setSoTimeout(timeOut);// 请求获取数据的超时时间(即响应时间)，单位毫秒。
//            client.getParams().setBooleanParameter( "http.protocol.expect-continue" , false );//Too many open files 解决
			client.executeMethod(post);
			resp = post.getResponseBodyAsString();
			if (resp != null && resp != "" && "&lt;".indexOf(resp) != -1) {
				resp = resp.replace("&lt;", "<");
				resp = resp.replace("&gt;", ">");
			}
		} catch (Exception e) {
            logger.error("===========" + url + "请求错误");
            logger.error("===========" + url + "call Exception===============", e);
		}
        logger.info("===========WebServiceProcessor resp===============" + resp);
        return resp == null ? "" : resp;
	}

    private String sendWebSevice2(CallParam callParam,String param,String url) {
        logger.info("===============sendWebSevice2 start===========");
        logger.info("===========WebServiceProcessor url===============" + url);
        logger.info("===========WebServiceProcessor param===============" + param);
        logger.info("=============send_request_time:"+ DateUtil.DateToStr(new Date(), "yyyy-MM-dd HH:mm:ss"));
        try {
        	JSONObject parseObject = JSONObject.parseObject(param);
            parseObject.remove("jf3_flag");
            param=parseObject.toJSONString();
		} catch (Exception e) {
            logger.error("===========" + url + "请求错误");
            logger.error("===========" + url + "call Exception===============", e);
        }
        String resp = "";
        PostMethod post = new PostMethod(url);
        try {
            RequestEntity requestEntity = new StringRequestEntity(param, "application/json", "UTF-8");
            post.setRequestEntity(requestEntity);
            HttpClient client = new HttpClient();
            client.getHttpConnectionManager().getParams().setConnectionTimeout(5*1000);//连接超时
            client.getHttpConnectionManager().getParams().setSoTimeout(5*1000);//等待结果超时
            try {
                client.executeMethod(post);
            } catch (HttpException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                resp = post.getResponseBodyAsString();
                logger.info("===========完成http请求==============="+resp);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return resp == null ? "" : resp;
    }
	
	public int endProcess(CallParam callParam) {
		logger.info("callParam.getServiceResultCode()----" + callParam.getServiceResultCode());
		if (Constants.LOG.isDebugEnabled()) {
			Constants.LOG.debug("ForwardProcessor handleAnswer");
		}
		callParam.getAsynHandler().onCallResult(callParam);
		return 0;
	}

	public WHConfigService getWhConfigService() {
		return whConfigService;
	}

	public void setWhConfigService(WHConfigService whConfigService) {
		this.whConfigService = whConfigService;
	}

}
